#pragma once

#include "Sock.hpp"
#include <functional>
#include<vector>
#include<pthread.h>

namespace ns_tcpserver
{
    using func_t = std::function<void(int)>;
    class TcpServer;
    class ThreadData
    {
    public:
        ThreadData(int sock,TcpServer* server): sock_(sock),server_(server)
        {}
        ~ThreadData() {}

    public:
        int sock_;
        TcpServer *server_;
    };
    class TcpServer
    {
    private:
        static void *ThreadRoutine(void *args)
        {
            pthread_detach(pthread_self());
            ThreadData* td=static_cast<ThreadData* >(args);
            td->server_->Excute(td->sock_);
            close(td->sock_);
            delete td;
            return nullptr;
        }

    public:
        TcpServer(const uint16_t &port, const std::string &ip = "0.0.0.0")
        {
            _listensock = _sock.Socket();
            _sock.Bind(_listensock, port, ip);
            _sock.Listen(_listensock);
        }
        void BindService(func_t func)
        {
            _func.push_back(func);
        }
        void Excute(int sock)
        {
            for(auto &f : _func)
            {
                f(sock);
            }
        }
        void Start()
        {
            for (;;)
            {
                uint16_t clientport;
                std::string clientip;
                int sock = _sock.Accept(_listensock, &clientip, &clientport);
                if (sock == -1)
                    continue;
                logMessage(NORMAL, "create new link success,sock:%d", sock);
                pthread_t tid;
                ThreadData* td=new ThreadData(sock,this);
                pthread_create(&tid, nullptr, ThreadRoutine, td);
            }
        }
        ~TcpServer()
        {
            if (_listensock >= 0)
                close(_listensock);
        }

    private:
        int _listensock;
        Sock _sock;
        std::vector<func_t> _func;
    };
}